package com.wechat;

import com.wechat.redis.RedisUtils;
import com.wechat.websocket.netty.NettyWebSocketStarter;
import io.lettuce.core.RedisConnectionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;

@Component
@Slf4j
public class InitRun implements ApplicationRunner {
    @Resource
    private DataSource dataSource;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private NettyWebSocketStarter nettyWebSocketStarter;
    /*
     启动时启动，实现netty的生命周期与主程序一致，且是异步启动
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            dataSource.getConnection();
            redisUtils.get("test");
            new Thread(nettyWebSocketStarter).start();//新建线程执行，netty独立线程启动，与主线程不阻塞
//            nettyWebSocketStarter.run();//在当前线程执行，若run()内有阻塞操作，主线程可能会阻塞
            log.info("初始化成功");
        } catch (SQLException e) {
            log.error("数据库连接失败");
            e.printStackTrace();
        }catch (RedisConnectionException e) {
            log.error("redis连接失败");
            e.printStackTrace();
        }catch (Exception e) {
            log.error("初始化失败");
            e.printStackTrace();
        }
    }
}
